<template>
  <div class="match-list-container">
    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="比赛名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入比赛名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="比赛状态">
          <el-select
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="未开始" value="pending" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已结束" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>

        <el-form-item label="运动类型">
          <el-select
            v-model="searchForm.sportType"
            placeholder="选择运动类型"
            clearable
            style="width: 150px"
          >
            <el-option label="篮球" value="basketball" />
            <el-option label="羽毛球" value="badminton" />
            <el-option label="足球" value="football" />
            <el-option label="网球" value="tennis" />
            <el-option label="乒乓球" value="pingpong" />
          </el-select>
        </el-form-item>

        <el-form-item label="比赛级别">
          <el-select
            v-model="searchForm.level"
            placeholder="选择级别"
            clearable
            style="width: 150px"
          >
            <el-option label="国际级" value="international" />
            <el-option label="国家级" value="national" />
            <el-option label="省级" value="provincial" />
            <el-option label="市级" value="city" />
            <el-option label="区级" value="district" />
            <el-option label="业余级" value="amateur" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline icon="ep:search" class="mr-1" />
            搜索
          </el-button>
          <el-button @click="resetSearch"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-bar">
        <div class="action-left">
          <el-button type="primary" @click="handleCreate">
            <IconifyIconOffline icon="ep:plus" class="mr-1" />
            创建比赛
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedMatches.length === 0"
            @click="handleBatchDelete"
          >
            <IconifyIconOffline icon="ep:delete" class="mr-1" />
            批量删除
          </el-button>
          <el-button @click="handleExport">
            <IconifyIconOffline icon="ep:download" class="mr-1" />
            导出数据
          </el-button>
        </div>

        <div class="action-right">
          <el-button @click="handleRefresh">
            <IconifyIconOffline icon="ep:refresh" class="mr-1" />
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 比赛列表 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="matchList"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column label="比赛封面" width="100">
          <template #default="{ row }">
            <el-image
              :src="row.cover"
              :alt="row.name"
              style="width: 60px; height: 60px; border-radius: 4px"
              fit="cover"
              :preview-src-list="[row.cover]"
              preview-teleported
            />
          </template>
        </el-table-column>

        <el-table-column prop="name" label="比赛名称" min-width="180">
          <template #default="{ row }">
            <div class="match-name">
              <div class="name">{{ row.name }}</div>
              <div v-if="row.subtitle" class="subtitle">{{ row.subtitle }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="sportType" label="运动类型" width="100">
          <template #default="{ row }">
            {{ getSportTypeName(row.sportType) }}
          </template>
        </el-table-column>

        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            {{ getLevelName(row.level) }}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="参赛队伍" width="120">
          <template #default="{ row }">
            <div class="team-info">
              <span class="current">{{ row.currentTeams }}</span>
              <span class="divider">/</span>
              <span class="max">{{ row.maxTeams }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="registrationFee" label="报名费" width="100">
          <template #default="{ row }">
            <span v-if="row.registrationFee === 0" class="free-tag">免费</span>
            <span v-else class="fee-tag">¥{{ row.registrationFee }}</span>
          </template>
        </el-table-column>

        <el-table-column label="比赛时间" width="160">
          <template #default="{ row }">
            <div class="time-info">
              <div class="start-time">{{ formatDate(row.startDate) }}</div>
              <div class="end-time">{{ formatDate(row.endDate) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="organizer" label="主办方" width="120" />

        <el-table-column prop="creator" label="创建人" width="100" />

        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              link
              size="small"
              @click="handleResult(row)"
            >
              结果
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import dayjs from "dayjs";

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  name: "",
  status: "",
  sportType: "",
  level: "",
  createTimeRange: []
});

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 加载状态
const loading = ref(false);

// 选中的比赛
const selectedMatches = ref([]);

// 比赛列表
const matchList = ref([
  {
    id: 1,
    name: "2024年春季篮球联赛",
    subtitle: "青少年篮球比赛",
    cover:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=basketball%20tournament%20poster%2C%20youth%20competition%2C%20sports%20event&image_size=square",
    sportType: "basketball",
    level: "city",
    status: "ongoing",
    currentTeams: 16,
    maxTeams: 32,
    registrationFee: 500,
    startDate: "2024-03-15",
    endDate: "2024-03-25",
    organizer: "市体育局",
    creator: "张管理员",
    createTime: "2024-02-01 10:00:00"
  },
  {
    id: 2,
    name: "羽毛球公开赛",
    subtitle: "全民健身羽毛球比赛",
    cover:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=badminton%20tournament%20poster%2C%20open%20championship%2C%20professional%20sports&image_size=square",
    sportType: "badminton",
    level: "amateur",
    status: "pending",
    currentTeams: 8,
    maxTeams: 16,
    registrationFee: 0,
    startDate: "2024-04-01",
    endDate: "2024-04-03",
    organizer: "羽毛球协会",
    creator: "李管理员",
    createTime: "2024-02-15 14:30:00"
  },
  {
    id: 3,
    name: "足球友谊赛",
    subtitle: "企业足球联谊赛",
    cover:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=football%20tournament%20poster%2C%20corporate%20friendly%20match%2C%20team%20sports&image_size=square",
    sportType: "football",
    level: "amateur",
    status: "completed",
    currentTeams: 12,
    maxTeams: 12,
    registrationFee: 300,
    startDate: "2024-02-20",
    endDate: "2024-02-22",
    organizer: "企业联盟",
    creator: "王管理员",
    createTime: "2024-01-20 09:15:00"
  }
]);

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format("MM-DD");
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format("YYYY-MM-DD HH:mm");
};

// 获取运动类型名称
const getSportTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    basketball: "篮球",
    badminton: "羽毛球",
    football: "足球",
    tennis: "网球",
    pingpong: "乒乓球"
  };
  return typeMap[type] || type;
};

// 获取级别名称
const getLevelName = (level: string) => {
  const levelMap: Record<string, string> = {
    international: "国际级",
    national: "国家级",
    provincial: "省级",
    city: "市级",
    district: "区级",
    amateur: "业余级"
  };
  return levelMap[level] || level;
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "info",
    ongoing: "warning",
    completed: "success",
    cancelled: "danger"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "未开始",
    ongoing: "进行中",
    completed: "已结束",
    cancelled: "已取消"
  };
  return statusMap[status] || "未知";
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  loadMatchList();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    name: "",
    status: "",
    sportType: "",
    level: "",
    createTimeRange: []
  });
  handleSearch();
};

// 创建比赛
const handleCreate = () => {
  router.push("/match/create");
};

// 查看比赛
const handleView = (row: any) => {
  router.push(`/match/detail/${row.id}`);
};

// 编辑比赛
const handleEdit = (row: any) => {
  router.push(`/match/edit/${row.id}`);
};

// 比赛结果
const handleResult = (row: any) => {
  router.push(`/match/result/${row.id}`);
};

// 删除比赛
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除比赛 "${row.name}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用API删除比赛
    ElMessage.success("删除成功");
    loadMatchList();
  } catch {
    // 用户取消
  }
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedMatches.value.length} 个比赛吗？`,
      "确认批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用API批量删除
    ElMessage.success("批量删除成功");
    selectedMatches.value = [];
    loadMatchList();
  } catch {
    // 用户取消
  }
};

// 导出数据
const handleExport = () => {
  // 这里应该调用导出API
  ElMessage.success("导出成功");
};

// 刷新
const handleRefresh = () => {
  loadMatchList();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedMatches.value = selection;
};

// 页面大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadMatchList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadMatchList();
};

// 加载比赛列表
const loadMatchList = async () => {
  loading.value = true;
  try {
    // 这里应该调用API获取比赛列表
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));

    // 更新分页信息
    pagination.total = matchList.value.length;

    ElMessage.success("数据加载完成");
  } catch (error) {
    ElMessage.error("加载失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadMatchList();
});
</script>

<style scoped lang="scss">
.match-list-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .action-left,
  .action-right {
    display: flex;
    gap: 8px;
  }
}

.match-name {
  .name {
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
  }

  .subtitle {
    font-size: 12px;
    color: #909399;
  }
}

.team-info {
  display: flex;
  align-items: center;

  .current {
    color: #409eff;
    font-weight: 600;
  }

  .divider {
    margin: 0 4px;
    color: #c0c4cc;
  }

  .max {
    color: #909399;
  }
}

.free-tag {
  color: #67c23a;
  font-weight: 600;
}

.fee-tag {
  color: #e6a23c;
  font-weight: 600;
}

.time-info {
  .start-time {
    color: #303133;
    font-size: 14px;
    margin-bottom: 2px;
  }

  .end-time {
    color: #909399;
    font-size: 12px;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .match-list-container {
    padding: 10px;
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left,
    .action-right {
      justify-content: center;
    }
  }

  .el-form {
    .el-form-item {
      margin-bottom: 16px;
    }
  }
}
</style>
